local digToAir = function(digFunc)
    local flag = nil
    repeat
        flag = digFunc()
    until (not flag)
end

local repeatAction = function(actionFunc, times)
    for i=1, times do
        actionFunc()
    end
end

local digAction = function()
    digToAir(turtle.dig)
    turtle.forward()
    digToAir(turtle.digUp)
end

local placeTorch = function()
    TORCH_SLOTS = {13, 14, 15, 16}
    torchSlot = -1
    for i, slot in ipairs(TORCH_SLOTS) do
        if(turtle.getItemDetail(slot).name == "minecraft:torch") then
            torchSlot = slot
            break
        end
    end
    if(torchSlot ~= -1) then
        turtle.select(torchSlot)
        return turtle.place()
    end
    return false
end


args = {...}

local BRANCH_CNT = tonumber(args[1])
local BRANCH_LEN = 32

local turnFunc = {}
turnFunc[1] = turtle.turnLeft
turnFunc[-1] = turtle.turnRight

local direction = 1
for i=1, BRANCH_CNT do
    repeatAction(digAction, 2)
    turnFunc[direction]()
    repeatAction(digAction, BRANCH_LEN)
    repeatAction(turnFunc[direction], 2)

    for j=1, BRANCH_LEN do
        digAction()
        if(j%8 == 5) then
            repeatAction(turnFunc[direction], 2)
            placeTorch()
            repeatAction(turnFunc[direction], 2)
        end
    end
    
    turnFunc[direction]()
    direction = -direction
end
